<?php
	/**
	 * ITsnp
	 * v1.0
	 * ./class/db.class.php
	 * TODO:数据库类
	 * Create：2008-05-21
	 * Modify：2008-05-23
	 * Pocky@best WorkGroup.
	 */
	class DB {
		var $host = false;
		var $port = 3306;
		var $user = false;
		var $password = false;
		var $dbname = false;
		var $dbcharset = null;
		var $dbcollate = null;
		var $num_queries      = 0;
		var $last_query       = null;
		var $last_error       = null;
		var $cache_dir        = CAC;
		var $cache_queries    = false;
		var $cache_inserts    = false;
		var $use_disk_cache   = false;
		var $cache_timeout    = 3600; // sec
		var $col_info         = null;
		var $pconnect=false;
		function DB(){
			global $syscfg;
			$this->host=$syscfg['mysql']['DB_HOST'];
			if (isset($syscfg['mysql']['DB_PORT']) && $syscfg['mysql']['DB_PORT']!=0)
				$this->port=$syscfg['mysql']['DB_HOST'];
			$this->user=$syscfg['mysql']['DB_USER'];
			$this->password=$syscfg['mysql']['DB_PASSWORD'];
			$this->dbname=$syscfg['mysql']['DB_NAME'];
			$this->dbcharset=$syscfg['mysql']['DB_CHARSET'];
			$this->dbcollate=$syscfg['mysql']['DB_COLLATE'];
			$this->pconnect=$syscfg['mysql']['DB_PCONNECT'];
			$this->use_disk_cache=$syscfg['mysql']['DB_DISTCACHE'];
			$this->cache_timeout=$syscfg['mysql']['DB_CACHETIME'];
			$this->quickConnect();
		}
		
		function quickConnect(){
			$flag_return=false;
			if( ! $this->connect() );
			else 
				if(! $this->select($this->dbname));
				else $flag_return=true;
			return $flag_return;
		}
		
		function connect(){
			$flag_return = false;
			if($this->pconnect){
				if ( ! $this->lnk = @mysql_pconnect($this->host.':'.$this->port,
						$this->user,$this->password,true) ){
					$this->errorLog(date('Y-m-d H:i:s',time()).' in '.__FILE__.' on line '.__LINE__);
				}else
					$flag_return = true;
			}else{
				if ( ! $this->lnk = @mysql_connect($this->host,$this->user,$this->password,true) ){
					$this->errorLog(date('Y-m-d H:i:s',time()).' in '.__FILE__.' on line '.__LINE__);
				}else
					$flag_return = true;
			}
			return $flag_return;
		}
		
		function select(){
			$flag_return=false;
			if (!$this->dbname){
				$this->errorLog(date('Y-m-d H:i:s',time()).'The database name is null,please set the config files');
			}else if ( ! $this->lnk ){
				$this->errorLog(date('Y-m-d H:i:s',time()).' in '.__FILE__.' on line '.__LINE__);			
			}
			else if ( !@mysql_select_db($this->dbname,$this->lnk) ){
				if ( !$str = @mysql_error($this->lnk))
					$this->errorLog(date('Y-m-d H:i:s',time()).$str.' in '.__FILE__.' on line '.__LINE__);
			}else{
				$flag_return = true;
			}
			return $flag_return;
		}
		
		function escape($str){
			return mysql_escape_string(stripslashes($str));
		}
		
		function flush(){
			$this->last_result = null;
			$this->col_info = null;
			$this->last_query = null;
			$this->from_disk_cache = false;
		}
		
		function getCache($query){
			$cache_file = $this->cache_dir.md5($query);
			if ( $this->use_disk_cache && file_exists($cache_file) ){
				if ( (time() - filemtime($cache_file)) >($this->cache_timeout) ){
					unlink($cache_file);
					return 0;
				}else{
					$result_cache = unserialize(file_get_contents($cache_file));
					$this->col_info = $result_cache['col_info'];
					$this->last_result = $result_cache['last_result'];
					$this->num_rows = $result_cache['num_rows'];
					$this->from_disk_cache = true;
					return $result_cache['return_value'];
				}
			}
			return false;
		}
		
		function storeCache($query){
			$cache_file = $this->cache_dir.'/'.md5($query);
			if ( $this->use_disk_cache ){
				if ( ! is_dir($this->cache_dir) ){
					$this->errorLog(date('Y-m-d H:i:s',time())."Could not open cache dir: $this->cache_dir");
				}else{
					$result_cache = array
					(
						'col_info' => $this->col_info,
						'last_result' => $this->last_result,
						'num_rows' => $this->num_rows,
						'return_value' => $this->num_rows,
					);
					error_log(serialize($result_cache), 3, $cache_file);
				}
			}
		}	
		function query($query){		
			$return_val = 0;
			$this->flush();
			$query = trim($query);	
			if($query=='') return $return_val;
			$query=$this->escape($query);
			$this->Log($query);
			$this->last_query = $query;
			$this->num_queries++;
			if ( $cache = $this->getCache($query) ){
				return $cache;
			}
			if (!isset($this->lnk) || !$this->lnk){
				$this->connect($this->user, $this->password, $this->host);
				if ( !empty($this->charset) && version_compare(mysql_get_server_info($this->dbh), '4.1.0', '>=') )
	 			$this->query("SET NAMES '$this->charset'");
				$this->select($this->dbname);
			}
			$this->result = @mysql_query($query,$this->lnk);
			if ( $str = @mysql_error($this->lnk) ){				
					$this->errorLog($str);
					return $return_val;
			}		
			if ( preg_match("/^(insert|delete|update|replace)\s+/i",$query) ){
				$this->rows_affected = @mysql_affected_rows();
				if ( preg_match("/^(insert|replace)\s+/i",$query) ){
					$this->insert_id = @mysql_insert_id($this->lnk);
				}
				$return_val = $this->rows_affected;
			}else{
				$i=0;
				while ($i < @mysql_num_fields($this->result)){
					$this->col_info[$i] = @mysql_fetch_field($this->result);
					$i++;
				}
				$num_rows=0;
				while ( $row = @mysql_fetch_object($this->result) ){
					$this->last_result[$num_rows] = $row;
					$num_rows++;
				}
				@mysql_free_result($this->result);
				$this->num_rows = $num_rows;
				$return_val = $this->num_rows;
			}
			$this->storeCache($query);
			return $return_val;
		}
		function Log($query){
			//echo $query.'<br />';
		}
		function errorLog($info){
			//echo $info.'<br />';
		}
	}
?>